import React, { useEffect, useRef, useState } from 'react'
import { Steps, PageHeader, Button, Form, Input, Select, notification } from 'antd';
import styled from './css/Newsadd.module.css'
import axios from 'axios';
import Myeditor from '../../../components/news/Myeditor';
import { useNavigate } from 'react-router-dom';

const { Step } = Steps;
const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

export default function Newsadd() {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [categories, setCategories] = useState([]);
  const [newsInfo, setNewsInfo] = useState({});
  const [content, setContent] = useState()
  const ref1 = useRef();
  let { region, username, roleId } = JSON.parse(localStorage.getItem('token'));
  const navigate = useNavigate();
  useEffect(()=>{
    axios({
      url:'/categories'
    }).then(res =>
      setCategories(res.data));
  },[])
  const newssubmit = (valuetype) =>{
    axios.post('/news',{
      title: newsInfo.newstitle,
      categoryId: newsInfo.newstype,
      content: content,
      region: region ? region:'全球',
      author: username,
      roleId: roleId,
      auditState: valuetype,
      publishState: 0,
      createTime: Date.now(),
      star: 0,
      view: 0,
    }).then(res => {
       if(valuetype === 0){
        navigate('/sandbox/news/draft')
        notification.info({
          message: `消息提示`,
          description:
            '本条新闻已成功导入进草稿箱',
        });
       }
       else{
        navigate('/sandbox/audit/list')
        notification.info({
          message: `消息提示`,
          description:
            '本条新闻已成功导入进待审核列表',
        });
       }
    })
  } 
  return (
    <div>
      <PageHeader
        className="site-page-header"
        title="撰写新闻"
      />
      <Steps current={currentIndex}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主体内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>
      <div className={styled.detail}>
          <Form 
            {...layout} 
            className={currentIndex === 0? '':styled.hidden} 
            name="control-hooks" 
            labelAlign='left' 
            style={{width:'50%', margin:'0 auto', paddingTop:'5rem'}}
            ref={ref1}
          >
            <Form.Item
              name="newstitle"
              label="新闻标题："
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="newstype"
              label="新闻体裁"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select
                placeholder="选择你的新闻体裁"
                allowClear
              >
                {
                  categories.map(item => 
                    <Option key={item.id} value = {item.id}>{item.title}</Option>)
                }
              </Select>
            </Form.Item>
          </Form>
          <Myeditor currentIndex={currentIndex} getarticlevalue={(textvalue)=>{
            setContent(textvalue);
          }}></Myeditor>
          <div 
            className={currentIndex === 2? '':styled.hidden} 
            style={{textAlign:'center', 
            lineHeight:'18.75rem'}}
          >
            <h2>你确定要提交吗？可以保存到草稿箱哦~</h2>
          </div>
      </div>
      <div className={styled.buttonbox}>
        <div style={{width:'85%'}} className={styled.buttonbox3}>
          <Button className={currentIndex === 0? styled.hidden:''} onClick={()=>{
            if(currentIndex > 0){
              setCurrentIndex(currentIndex - 1);
            }
          }}>上一步</Button>
          <Button 
            type="primary" 
            style={{marginLeft:'1rem', zIndex:100}} 
            className={currentIndex === 2? styled.hidden:''} 
            onClick={()=>{
              if(currentIndex < 2){
                if(currentIndex === 0){
                  ref1.current.validateFields().then(res =>{ 
                    console.log(res)     //获取当前表单的所有值
                    setNewsInfo({
                      newstitle:res.newstitle,
                      newstype:res.newstype
                    })
                    if(res.length !== 0){
                      setCurrentIndex(currentIndex + 1);
                    }
                  })
                }
                else if(currentIndex === 1){
                  if(content ==="" || content ==="<p><br></p>")
                    alert("内容不允许为空")
                  else
                    setCurrentIndex(currentIndex + 1);
                }          
              }
            }}>下一步</Button>
        </div>
        <div className={styled.buttonbox2}>
          <Button 
            type="primary" 
            className={ currentIndex === 2? '':styled.hidden} 
            onClick={()=>{newssubmit(0)}}> 
              保存到草稿箱 
          </Button>
          <Button 
            type="primary" 
            danger 
            className={currentIndex === 2? '':styled.hidden} 
            style={{marginLeft:'.5rem'}} 
            onClick={()=>{newssubmit(1)}}> 
              提交 
          </Button>
        </div>
      </div>
    </div>
  )
}
